import React, { useState, useEffect } from 'react';
import _ from 'lodash';
import { connect } from 'dva';
import { Breadcrumb, Popover, Input, Tree, Icon } from 'antd';
import * as Utils from '../utils/index';

const { Search } = Input;
const TreeSearch = props => {
  const { dispatch, reduxItem } = props;
  const { orgIds, tree, getTree } = reduxItem;
  const [treeData, setTreeData] = useState([]);
  const [isEditingPath, setIsEditingPath] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [defaultSelectedKeys, setDefaultSelectedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(false);
  const [orgnames, setOrgnames] = useState([]);
  useEffect(() => {
    if (Object.keys(orgIds).length > 0) {
      const { orgnofullpath, orgdepid } = orgIds;
      const ids = orgnofullpath.split('-');
      const orgStructure = [];
      _.forEach(tree, val => {
        _.forEach(ids, x => {
          if (val.orgdepid === x) {
            orgStructure.push(val);
          }
        });
      });
      const orgnameList = Utils.getTreeOrgnameList(Utils.getTreeDatas(orgStructure));
      setDefaultSelectedKeys([orgdepid]);
      setOrgnames(orgnameList);
      setTreeData(getTree);
    }
  }, [orgIds]);

  const handlerSearchTree = value => {
    const searchDate = _.filter(
      props.reduxItem.tree,
      val => _.toUpper(_.trim(val.orgname)).indexOf(_.toUpper(_.trim(value))) > -1,
    );
    let ids = [];
    const orgStructure = [];
    _.forEach(searchDate, val => {
      _.forEach(val.orgnofullpath.split('-'), data => {
        ids.push(data);
      });
    });
    ids = _.uniq(ids);
    _.forEach(props.reduxItem.tree, val => {
      _.forEach(ids, data => {
        if (val.orgdepid === data) {
          orgStructure.push(val);
        }
      });
    });
    setExpandedKeys(value ? ids : []);
    setAutoExpandParent(false);
    setTreeData(Utils.getTreeDatas(orgStructure));
  };

  const handlerChangeTreeVal = (selectedKeys, info) => {
    const { orgnofullpath, hrOrgTypeId, orgdepid } = info.node.props;
    setDefaultSelectedKeys([orgdepid]);
    dispatch({
      type: 'MonitoringConsole/getOrgIds',
      payload: {
        orgIds: {
          ...orgIds,
          orgdepid,
          hrOrgTypeId,
          orgnofullpath,
        },
        getTree,
      },
    });
    setIsEditingPath(false);
  };

  const onExpand = exp => {
    setExpandedKeys(exp);
    setAutoExpandParent(false);
  };

  return (
    <Popover
      placement="topLeft"
      title=""
      visible={isEditingPath}
      onVisibleChange={() => setIsEditingPath(!isEditingPath)}
      content={
        <>
          <Search placeholder="请输入关键字" onSearch={value => handlerSearchTree(value)} />
          <Tree
            placeholder="请选择项目"
            style={{ maxHeight: 300, overflow: 'auto' }}
            treeData={treeData}
            onSelect={handlerChangeTreeVal}
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            defaultSelectedKeys={defaultSelectedKeys}
            autoExpandParent={autoExpandParent}
          />
        </>
      }
      trigger="click"
    >
      {_.isEmpty(orgnames) ? (
        <Icon type="loading" />
      ) : (
        <div style={{ cursor: 'pointer' }}>
          <Breadcrumb>
            {orgnames.map((val, index) => {
              if (index === orgnames.length - 1 && orgnames.length !== 1) {
                return null;
              }
              return <Breadcrumb.Item key={val}>{val}</Breadcrumb.Item>;
            })}
          </Breadcrumb>
          <div style={{ fontSize: '14px' }}>
            <span>{orgnames[orgnames.length - 1]}</span>
            <Icon type={isEditingPath ? 'down' : 'up'} size="small" />
          </div>
        </div>
      )}
    </Popover>
  );
};

export default connect(state => ({
  reduxItem: state.MonitoringConsole,
}))(TreeSearch);
